package HtServer.Tools;

import HtServer.meeting.MeetingItems;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import tools.Configure;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Hashtable;

public class QrCodeUtils {
    private static final String CHARSET = "utf-8";
    public static final String FORMAT = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    public static BufferedImage createImage(String content) throws Exception {
        return createImage(content, null);
    }
    /**
     * 生成二维码
     * @param content      二维码内容
     * @return 图片
     * @throws Exception
     */
    public static BufferedImage createImage(String content,String overlayText) throws Exception {
        // 二维码参数设置
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        // 安全等级，最高h
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 编码设置
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        // 设置margin=0-10
        hints.put(EncodeHintType.MARGIN, 1);
        // 创建矩阵容器
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


        if (overlayText != null) {
            BufferedImage overlay = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = overlay.createGraphics();
            g2d.setColor(Color.RED);
            g2d.setFont(new Font("Arial", Font.BOLD, 40));
            FontMetrics fm = g2d.getFontMetrics();
            int textWidth = fm.stringWidth(overlayText);
            int textHeight = fm.getHeight();
            g2d.drawString(overlayText, (width - textWidth) / 2, (height + textHeight) / 4);
            g2d.dispose();


            Graphics2D combined = image.createGraphics();
            combined.drawImage(overlay, 0, 0, null);
            combined.dispose();

        }


        // 矩阵转换图像
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }


    /**
     * 生成二维码
     *
     * @param content      内容
     * @param output       输出流
     * @throws Exception
     */
    public static void encode(String content, OutputStream output)
            throws Exception {
        BufferedImage image = QrCodeUtils.createImage(content);
        ImageIO.write(image, FORMAT, output);
    }

    @Deprecated
    public static BufferedImage generateQRCodeImage(String text, int width, int height, String filePath, String overlayText)
            throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        // Create overlay text image
//        BufferedImage overlay = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = qrImage.createGraphics();
        g2d.setColor(Color.RED);
        g2d.setFont(new Font("Arial", Font.BOLD, 40));
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(overlayText);
        int textHeight = fm.getHeight();
        g2d.drawString(overlayText, (width - textWidth) / 2, (height + textHeight) / 2);
        g2d.dispose();

        // Combine QR code and overlay
//        Graphics2D combined = qrImage.createGraphics();
//        combined.drawImage(overlay, 0, 0, null);
//        combined.dispose();

        // Save combined image
//        Path path = FileSystems.getDefault().getPath(filePath);
//        ImageIO.write(qrImage, "PNG", path.toFile());

        return qrImage;
    }

    public static void main(String[] args) {
        try {
//            BufferedImage image = generateQRCodeImage("requestUrl",300,300, "/Users/zgw/temp/qrcode.png","overlayText");
//                BufferedImage image = ImageIO.read(file);

//            BufferedImage image = createImage("http://192.168.1.6:2800/#/meetinggroupMobile?groupid=2");
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            ImageIO.write(image, "PNG", baos);
//            String str ="data:image/png;base64,"+ Base64.getEncoder().encodeToString(baos.toByteArray());
//            System.out.println(str);


            HashMap<String,String> groupNames = MeetingItems.getInstance().getGroupNames();


            JSONArray jsonArray = new JSONArray();
            for (String key : groupNames.keySet()) {
                System.out.println("key= "+ key + " and value= " + groupNames.get(key));

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("groupname",groupNames.get(key));
                jsonObject.put("groupid",key);



                String url = Configure.getInstance().getProperties().getProperty("group_qrcode");
                url = url+"?groupid="+key;
                try {
                    BufferedImage image = createImage(url);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(image, "PNG", baos);
                    String base64 = Base64.getEncoder().encodeToString(baos.toByteArray());
                    jsonObject.put("base64",base64);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                jsonArray.add(jsonObject);
            }


            System.out.println(jsonArray.toJSONString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
